import re
from functools import wraps

from loguru import logger
from fastapi import Request


def replace_placeholders(log_message, **kwargs):
    def replace(match):
        key = match.group(1)
        keys = key.split('.')  # 将占位符拆分成属性列表
        value = kwargs
        for k in keys:
            if isinstance(value, dict):
                value = value.get(k, '')  # 逐级获取属性值
            elif hasattr(value, k):
                value = getattr(value, k)
            else:
                value = ''
                break
        return str(value)

    pattern = r'\{([\w.]+)\}'  # 匹配包含属性的占位符
    return re.sub(pattern, replace, log_message)


def log_action(log_message):
    def decorator(func):
        @wraps(func)
        async def wrapper(request: Request, *args, **kwargs):
            temp_str = replace_placeholders(log_message, **kwargs)
            request.scope['action'] = temp_str
            return await func(request, *args, **kwargs)

        return wrapper

    return decorator
